package com.guigu.qingcheng.orderservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.qingcheng.orderservice.mapper.TbPreferentialMapper;
import com.guigu.qingcheng.orderservice.service.TbPreferentialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.qingcheng.pojo.order.TbPreferential;
import com.guigu.qingcheng.utils.R;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbPreferentialServiceImpl extends ServiceImpl<TbPreferentialMapper, TbPreferential> implements TbPreferentialService {

    @Override
    public R findPage(Integer page, Integer size, Map<String, Object> searchMap) {
        Page<TbPreferential> tbPreferentialPage = new Page<>(page,size);

        QueryWrapper<TbPreferential> wrapper = new QueryWrapper<>();
        if (searchMap != null) {
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id")))
                wrapper.eq("id",searchMap.get("id"));
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name")))
                wrapper.like("name",searchMap.get("name"));
        }
        baseMapper.selectPage(tbPreferentialPage,wrapper);
        return R.ok().data("total",tbPreferentialPage.getTotal()).data("rows",tbPreferentialPage.getRecords());
    }

    @Override
    public int findPreMoneyByCategoryId(Integer categoryId, int money) {
        QueryWrapper<TbPreferential> wrapper = new QueryWrapper<>();
        wrapper.eq("state","1");//状态
        wrapper.eq("category_id",categoryId);
        wrapper.le("buy_money",money);
        wrapper.ge("end_time",new Date());
        wrapper.le("start_time",new Date());
        wrapper.orderByDesc("buy_money");
        List<TbPreferential> list = baseMapper.selectList(wrapper);
        if (list.size()>=1) {
            TbPreferential preferential = list.get(0);
            if ("1".equals(preferential.getType())) {
                //不翻倍
                return preferential.getBuyMoney();
            }else{
                //翻倍
                int qian = money/list.get(0).getBuyMoney();
                return qian*preferential.getPreMoney();
            }
        }else{
            return 0;
        }
    }
}
